package com.njtech.smartuniversity.controller;


import com.njtech.smartuniversity.util.JsonResult;
import com.njtech.smartuniversity.util.JsonUtil;
import com.njtech.smartuniversity.util.QiniuUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by ritchie on 7/5/18
 */
@RestController
@RequestMapping("/api/images")
@Api(value = "/api/images", tags = {"图片"}, description = "图片相关")
public class ImgController {

    @Autowired
    QiniuUtil mQiniuUtil;


//    @PutMapping("/upload")
//    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MERCHANT')")
//    @ApiOperation(value = "图片上传接口", notes = "图片上传")
//    @ApiImplicitParams({
//            @ApiImplicitParam(value = "图片", name = "image", dataType = "file", paramType = "form", required = true)
//    })
//    public JsonResult uploadImgQiniu(@RequestParam("image") MultipartFile multipartFile) throws IOException {
//        FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
//        long time = System.currentTimeMillis();
//
////        String path = mQiniuUtil.uploadImg(inputStream, time + "");
//        return new JsonUtil().successDataWithMessage(path, "图片上传成功");
//    }


    @PostMapping("/fileUpload")
//    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MERCHANT')")
    @ApiOperation(value = "图片上传接口", notes = "图片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "图片", name = "file", dataType = "file", paramType = "form")
    })

    public JsonResult fileUpload(@RequestParam("file") MultipartFile file){

        if(file.isEmpty()){
            return new JsonUtil().wrongNoDataWithMessage("文件为空");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        //获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "/www/wwwroot/wjxc-web/pages/system/cun/pic/";
        //新文件名
        fileName = UUID.randomUUID()+suffixName;
        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try{
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
        }
        String path = filePath+fileName;

        System.out.println(path);
        return new JsonUtil().successDataWithMessage(path, "图片上传成功");
    }

//    @ResponseBody
//    @RequestMapping("/upload")
//    @ApiOperation(value = "图片上传接口", notes = "图片上传")
//    @ApiImplicitParams({
//            @ApiImplicitParam(value = "图片", name = "files", dataType = "file", paramType = "form")
//    })
//    public JsonResult fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
////        // win系统 上传路径保存设置
////        // 获取项目路径
////        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
////        // 绝对路径=项目路径+自定义路径
////        File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
////        if (!pathFile.exists()) {
////            pathFile.mkdirs();
////        }
////        //上传文件地址
////        UUID uuid = UUID.randomUUID();
////        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
////        files.transferTo(serverFile);
////
////        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
////
////        return imgPath;
//
//        // Linux服务器  上传路径保存设置
//        // 项目路径  /home/www/
//        File pathFile = new File("/www/wwwroot/wjxc-master/pic/");
//        if (!pathFile.exists()) {
//            pathFile.mkdirs();
//        }
//        //上传文件地址
//        UUID uuid = UUID.randomUUID();
//        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
//        files.transferTo(serverFile);
//
//        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
//        return new JsonUtil().successDataWithMessage(imgPath, "图片上传成功");
//    }
//
//    @RequestMapping(value="/download")
//    public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
//        //要下载的图片地址
//        String  path = request.getServletContext().getRealPath("/upload");
//        String  fileName = "基础语法.jpg";
//
//        //1、设置response 响应头
//        response.reset(); //设置页面不缓存,清空buffer
//        response.setCharacterEncoding("UTF-8"); //字符编码
//        response.setContentType("multipart/form-data"); //二进制传输数据
//        //设置响应头
//        response.setHeader("Content-Disposition",
//                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
//
//        File file = new File(path,fileName);
//        //2、 读取文件--输入流
//        InputStream input=new FileInputStream(file);
//        //3、 写出文件--输出流
//        OutputStream out = response.getOutputStream();
//
//        byte[] buff =new byte[1024];
//        int index=0;
//        //4、执行 写出操作
//        while((index= input.read(buff))!= -1){
//            out.write(buff, 0, index);
//            out.flush();
//        }
//        out.close();
//        input.close();
//        return null;
//    }

}
